package TestDemo;

import java.util.Timer;
import java.util.concurrent.PriorityBlockingQueue;

class MyTimer {
    private Object locker = new Object();

    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTask myTask = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (myTask.getTime() > curTime) {
                            queue.put(myTask);
                            locker.wait(myTask.getTime() - curTime);
                        } else {
                            myTask.run();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long after) {
        MyTask myTask = new MyTask(runnable, after);
        synchronized (locker) {
            queue.put(myTask);
            locker.notify();
        }
    }
}

class MyTask implements Comparable<MyTask> {
    private Runnable command;

    private long time;

    public MyTask(Runnable command, long after) {
        this.command = command;
        this.time = after + System.currentTimeMillis();
    }

    public void run() {
        command.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}

public class TestDemo2 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3333");
            }
        }, 6000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1111");
            }
        }, 2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2222");
            }
        }, 4000);


    }
}
